﻿using System;
using System.Collections.Generic;
using System.Web;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using TheOutfield.UmbExt.UniversalMediaPicker.Xslt;
using umbraco;
using System.Xml;
using System.Xml.XPath;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.FileSystem
{
    public class FileSystemXsltExtension : AbstractXsltExtension
    {
        public static XPathNodeIterator GetMedia(int docTypeDefinitionId, string id)
        {
            var provider = GetProvider<FileSystemProvider>(docTypeDefinitionId);
            var service = new FileSystemService(provider.Config);

            try
            {
                var file = service.GetFile(id);

                var xd = new XmlDocument();
                var docNode = xmlHelper.addTextNode(xd, "File", "");

                if (file != null)
                {
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Id", file.FullName.Replace(service.RootDirPath, "\\")));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Name", file.Name));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Path", file.FullName));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Url", file.FullName.Replace(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath), "\\").Replace("\\", "/")));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Extension", file.Extension));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Length", file.Length.ToString()));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Size", String.Format(new FileSizeFormatProvider(), "{0:fs}", file.Length)));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Created", file.CreationTime.ToString("yyyy-MM-dd hh:mm:ss")));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Modified", file.LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss")));
                }

                xd.AppendChild(docNode);

                return xd.CreateNavigator().Select("/File");
            }
            catch (Exception e)
            {
                return e.ToXPathNodeIterator();
            }
        }
    }
}